package com.ruiysoft.controller.comment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.ruiysoft.entity.comment.CommentDTO;
import com.ruiysoft.entity.comment.CommentVo;
import com.ruiysoft.entity.comment.MerchandiseComment;
import com.ruiysoft.pub.core.Result;
import com.ruiysoft.pub.core.ResultGenerator;
import com.ruiysoft.service.comment.MerchandiseCommentService;
import com.ruiysoft.service.sys.clent.LoginContextUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @author fanyl
 */
@RestController
@RequestMapping(value = "/comment")
public class CommentController {

    private final MerchandiseCommentService merchandiseCommentService;

    public CommentController(MerchandiseCommentService merchandiseCommentService) {
        this.merchandiseCommentService = merchandiseCommentService;
    }


    /**
     * 新增评论
     *
     * @param commentDTO
     * @return
     */
    @PostMapping("/insert")
    public Result save(@RequestBody CommentDTO commentDTO) {
        if (ObjectUtils.isEmpty(commentDTO)) {
            return ResultGenerator.genFailResult("数据不能为空");
        }
        MerchandiseComment comment = new MerchandiseComment();
        BeanUtils.copyProperties(commentDTO, comment);

        if (org.springframework.util.StringUtils.hasText(comment.getPic())) {
            comment.setPic(StringUtils.join(commentDTO.getPic(), ","));
        }

        comment.setPersonalId(LoginContextUtil.instance().getEntryUser().getPersonnel().getId());
        comment.setUserId(LoginContextUtil.instance().getEntryUser().getSysUser().getId());
        comment.setShopId(LoginContextUtil.instance().getEntryMicroShop().getId());
        //新增评论默认状态为审核中
        comment.setCommentStatus(1);
        comment.setCreateDate(LocalDateTime.now());
        return ResultGenerator.genSuccessResult(merchandiseCommentService.save(comment));
    }

    @DeleteMapping("/del/{id}")
    public Result<Boolean> delete(@PathVariable Integer id) {
        return ResultGenerator.genSuccessResult(merchandiseCommentService.removeById(id));
    }

    @PutMapping("/update")
    public Result update(@RequestBody CommentDTO commentDTO) {
        if (ObjectUtils.isEmpty(commentDTO)) {
            return ResultGenerator.genFailResult("数据不能为空");
        }

//        MerchandiseComment comment = new MerchandiseComment();
//        BeanUtils.copyProperties(commentDTO, comment);
//        if (org.springframework.util.StringUtils.hasText(comment.getPic())) {
//            comment.setPic(StringUtils.join(commentDTO.getPic(), ","));
//        }

        MerchandiseComment comment = JSON.parseObject(JSON.toJSONString(commentDTO), new TypeReference<MerchandiseComment>() {});

        comment.setModifyDate(LocalDateTime.now());
        boolean rtn = merchandiseCommentService.updateById(comment);
        if(rtn)
            return ResultGenerator.genSuccessResult();
        else
            return ResultGenerator.genFailResult("更新失败");
    }

    @Transactional(rollbackFor = Exception.class)
    @DeleteMapping("/delete/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        if (ObjectUtils.isEmpty(ids)) {
            return ResultGenerator.genFailResult("参数不能为空");
        }
        return ResultGenerator.genSuccessResult(merchandiseCommentService.removeByIds(ids));
    }

//    @Cacheable(value = "commentPage")
    @GetMapping("/list/page")
    public Result<IPage> commentPage(@RequestParam Map<String, Object> params) {
        QueryWrapper queryWrapper = new QueryWrapper();
        String isAsc = (String) params.get("isAsc");
        long pageNum = Integer.parseInt(params.getOrDefault("pageNum", 1).toString());
        long pageSize = Integer.parseInt(params.getOrDefault("pageSize", 10).toString());
        Page<MerchandiseComment> page = new Page<>(pageNum, pageSize);

        params.remove("isAsc");
        params.remove("pageNum");
        params.remove("pageSize");

        queryWrapper.allEq(params);
        queryWrapper.orderBy(false, false, isAsc);

        return ResultGenerator.genSuccessResult(merchandiseCommentService.page(page, queryWrapper));
    }

    @GetMapping("/queryBySpuId")
    public  Result queryCommentBySpuId(@RequestParam("spuId") Integer spuId) {
        List<CommentVo> commentVos = merchandiseCommentService.queryBySpuId(spuId);
        if (CollectionUtils.isEmpty(commentVos)) {
            commentVos = Lists.newArrayList();
        }
        return ResultGenerator.genSuccessResult(commentVos);
    }
}
